//package com.alibaba.cirtus.ots.application.app.ability.facade;
//
//import com.alibaba.cz.base.tool.Nullable;
//import com.alibaba.cz.base.tool.log.Log;
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.alibaba.lattice2.epoch.sdk.model.Result;
//import com.epoch.app.bcots.model.dto.EmployeeGetCurrentLoginResponse;
//import com.epoch.app.bcots.model.dto.QueryCargoZoneListWithAccessRequest;
//import com.epoch.app.bcots.model.dto.QueryWarehouseByIdRequest;
//import com.epoch.app.bcots.model.dto.WarehouseInfo;
//import com.epoch.app.bcots.service.BcOtsService;
//import com.epoch.app.bcots.service.UnifiedInventoryService;
//import com.epoch.app.otsapplicationappsdk.detailplanreportalorder.dto.AsyncSubmitRequest;
//import com.epoch.app.otsapplicationappsdk.detailplanreportalorder.dto.RenderRequest;
//import com.epoch.app.otsapplicationappsdk.detailplanreportalorder.dto.SubmitRequest;
//import com.epoch.app.otsapplicationappsdk.detailplanreportalorder.service.DetailPlanReportalOrderService;
//import com.epoch.app.otsb2btradecenter.model.dto.OrderDetailsQueryRequest;
//import com.epoch.app.otsb2btradecenter.service.OtsB2bTradeCenterService;
//import com.epoch.app.otsforecastsales.api.forecastorderlinequery.service.ForecastOrderLineQueryService;
//import com.epoch.app.otsforecastsales.api.forecastorderlinewrite.service.ForecastOrderLineWriteService;
//import com.epoch.app.otsforecastsales.api.forecastorderwrite.service.ForecastOrderWriteService;
//import com.epoch.app.otsforecastsales.dto.request.DeleteForecastLineDetailRequest;
//import com.epoch.app.otsforecastsales.dto.request.SubmitForecastRequest;
//import com.epoch.app.otsforecastsales.dto.response.QueryForecastLineResponse;
//import com.epoch.app.otsforecastsales.enums.ForecastStatusEnum;
//import com.epoch.app.otsforecastsales.model.dto.ApiContext;
//import com.epoch.app.otsforecastsales.model.dto.*;
//import com.epoch.app.otsforecastsales.sdo.ForecastOrderLineSDO;
//import com.epoch.app.otsforecastsales.sdo.ForecastOrderSDO;
//import com.epoch.app.otsforecastsales.sdo.ScItemGoods;
//import com.epoch.app.otsforecastsales.service.OtsForecastSalesService;
//import com.epoch.app.otsplatformenhance.api.customeraddressquery.service.CustomerAddressQueryService;
//import com.epoch.app.otsplatformenhance.api.organizationquery.service.OrganizationQueryService;
//import com.epoch.app.otsplatformenhance.dto.request.IdQueryRequest;
//import com.epoch.app.otsplatformenhance.dto.request.QueryAddressRequest;
//import com.epoch.app.otsplatformenhance.goodsfavorites.dto.QueryGoodsFavoritesRequest;
//import com.epoch.app.otsplatformenhance.goodsfavorites.model.GoodsFavorites;
//import com.epoch.app.otsplatformenhance.goodsfavorites.service.GoodsFavoritesService;
//import com.epoch.app.otsplatformenhance.model.dto.*;
//import com.epoch.app.otsplatformenhance.sdo.CustomerAddressSDO;
//import com.epoch.app.otsplatformenhance.sdo.OrganizationSDO;
//import com.epoch.app.otsplatformenhance.service.OtsPlatformEnhanceService;
//import com.epoch.app.otspricecenter.api.creditquery.service.CreditQueryService;
//import com.epoch.app.otspricecenter.model.dto.CreditReponse;
//import com.epoch.app.otspricecenter.model.dto.QueryCreditRequest;
//import com.epoch.app.otsunifiedinventory.api.allocaterelationread.service.AllocateRelationReadService;
//import com.epoch.app.otsunifiedinventory.dto.request.QueryAllocateRelationRequest;
//import com.epoch.app.otsunifiedinventory.sdo.AllocateRelationSDO;
//import com.epoch.app.otsunifiedinventory.service.OtsUnifiedInventoryService;
//import com.google.gson.internal.LinkedTreeMap;
//import lombok.Data;
//import org.apache.commons.collections4.CollectionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.checkerframework.checker.units.qual.C;
//import org.springframework.beans.BeanUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import java.math.BigDecimal;
//import java.math.RoundingMode;
//import java.util.*;
//import java.util.concurrent.Callable;
//import java.util.concurrent.ExecutionException;
//import java.util.concurrent.Future;
//import java.util.concurrent.FutureTask;
//import java.util.stream.Collectors;
//
//@Service
//public class DetailPlanReportalOrderServiceImpl implements DetailPlanReportalOrderService {
//    private final static Log log = Log.getLogger(DetailPlanReportalOrderServiceImpl.class);
//    private static final int PLAN_ORDER_TYPE = 1;
//    public static final String SHANGHAI_ORG_CODE = "6255";
//    private static final List<Info> FILTER_ORDER_TYPE = new ArrayList<Info>() {{
//        add(new Info() {{
//            setLabel("标准预报订单");
//            setValue("01");
//        }});
//        /*add(new Info() {{
//            setLabel("车销预报订单");
//            setValue("02");
//        }});*/
//    }};
//
//
//    @Autowired
//    private OtsForecastSalesService otsForecastSalesService;
//
//    @Autowired
//    private OtsB2bTradeCenterService otsB2bTradeCenterService;
//
//
//    @Autowired
//    private OtsPlatformEnhanceService otsPlatformEnhanceService;
//
//    @Autowired
//    private OtsUnifiedInventoryService otsUnifiedInventoryService;
//
//    @Autowired
//    private UnifiedInventoryService unifiedInventoryService;
//
//    @Autowired
//    private ForecastOrderLineQueryService forecastOrderLineQueryService;
//
//    @Autowired
//    private ForecastOrderLineWriteService forecastOrderLineWriteService;
//
//    private static final String DATE_FORMAT_STR_STAN = "yyyy-MM-dd HH:mm:ss";
//
//
//    @Autowired
//    private ForecastOrderWriteService forecastOrderWriteService;
//
//
//    @Autowired
//    private CustomerAddressQueryService customerAddressQueryService;
//
//    @Autowired
//    private AllocateRelationReadService allocateRelationReadService;
//
//    @Autowired
//    private CreditQueryService creditQueryService;
//
//    @Autowired
//    private BcOtsService bcOtsService;
//
//    @Autowired
//    private OrganizationQueryService organizationQueryService;
//
//    @Autowired
//    private GoodsFavoritesService favoritesService;
//
//    @Override
//    public Object render(RenderRequest renderRequest) {
//
//        //从客户地址上取组织信息 如果没有异常，应取此货品集合
//        Future<List<ScItemGoods>> taskAddressScItem = null;
//
//        //单据类型集合
//        List<Info> filterOrderType = null;
//
//        //配送方式集合
//        List<Info> deliveryType = null;
//
//        //发货仓
//        List<Info> deliveryHouse = null;
//
//        CreateSelectList createSelectList = new CreateSelectList();
//        createSelectList.setDisableRefNo(Boolean.FALSE);
//
//        //是否需要加载列表项数据
//        Boolean needLoadSelectList = true;
//
//
//        /**
//         * inputType
//         * 1预报订单
//         * 2销售订单
//         * */
//        if (Objects.isNull(renderRequest) || StringUtils.isBlank(renderRequest.getOrderId()) || null == renderRequest.getInputType()) {
//            log.error("小程序预报销售订单详情入参数据异常:", JSONObject.toJSONString(renderRequest));
//            return null;
//        }
//        JSONObject forecastOrderSDO;
//        long l = System.currentTimeMillis();
//        if (PLAN_ORDER_TYPE == renderRequest.getInputType()) {
//            QueryForecastOrderResponse queryForecastOrderResponse = otsForecastSalesService.queryForecastOrder(new QueryForecastOrderRequest() {{
//                setId(renderRequest.getOrderId());
//            }});
//            forecastOrderSDO = JSONObject.parseObject(JSONObject.parseObject(JSONObject.toJSONString(queryForecastOrderResponse.getResult())).getString("forecastOrderSDO"));
//
//            Integer status = forecastOrderSDO.getInteger("status");
//            //待回复，待提交状态支持编辑 所有需要加载货品抽屉
//            if (status != ForecastStatusEnum.DRAFT.getNumValue() && status != ForecastStatusEnum.WAITING_FOR_REPLY.getNumValue()) {
//                needLoadSelectList = false;
//            }
//
//        } else {
//            forecastOrderSDO = JSONObject.parseObject(JSONObject.toJSONString(otsB2bTradeCenterService.orderDetailsQuery(new OrderDetailsQueryRequest() {{
//                setId(renderRequest.getOrderId());
//            }}).getResult()));
//
//            needLoadSelectList = false;
//
//        }
//        long l1 = System.currentTimeMillis();
//        log.info("查询详情耗时:" + (l1 - l));
//        log.info(JSONObject.toJSONString(forecastOrderSDO));
//
//        if (Objects.isNull(forecastOrderSDO) || StringUtils.isBlank(forecastOrderSDO.getString("addressCode"))) {
//            log.error("小程序预报销售订单详情数据异常:", JSONObject.toJSONString(forecastOrderSDO));
//            return null;
//        }
//        QueryAddressRequest queryAddressRequest = new QueryAddressRequest();
//        queryAddressRequest.setAddressCode(forecastOrderSDO.getString("addressCode"));
//        queryAddressRequest.setOrgSaleOrganizationCode(forecastOrderSDO.getString("organizationCode"));
//        queryAddressRequest.setOrgSaleChannelCode(forecastOrderSDO.getString("saleChannelCode"));
//        queryAddressRequest.setOrgSaleDepartmentCode(forecastOrderSDO.getString("departmentCode"));
//        queryAddressRequest.setPrincipal(forecastOrderSDO.getString("salesmanCode"));
//        Result<List<CustomerAddressSDO>> listResult = customerAddressQueryService.pageQueryCustomerAddress(queryAddressRequest);
//        if (Objects.nonNull(listResult) && CollectionUtils.isNotEmpty(listResult.getResult())) {
//            forecastOrderSDO.put("addressId",listResult.getResult().get(0).getId());
//        }
//
//        //收货地址 选中一条收货地址 查询出对应的客户信息和组织信息(风险，收货地址同一个addressCode可能有多条)
//        /*PageQueryAddressListByPrincipalResponse listResult = otsPlatformEnhanceService.pageQueryAddressListByPrincipal(new PageQueryAddressListByPrincipalRequest() {{
//            setAddressCode(forecastOrderSDO.getString("addressCode"));
//        }});
//*/
//        long l3 = System.currentTimeMillis();
//        log.info("查询收货地址耗时:" + (l3 - l1));
//        if (needLoadSelectList) {
//         //   if (Objects.nonNull(listResult) && CollectionUtils.isNotEmpty(listResult.getResult())) {
//                //LinkedTreeMap relationInfo = (LinkedTreeMap) listResult.getResult().get(0);
//
//                String channelCode = forecastOrderSDO.getString("channelCode");
//                String organizationCode = forecastOrderSDO.getString("organizationCode");
//                String orgSaleDepartmentCode = forecastOrderSDO.getString("departmentCode");
//                String orgSaleChannelCode = forecastOrderSDO.getString("saleChannelCode");
//                String salesmanCode = forecastOrderSDO.getString("salesmanCode");
//                String warehouseCode = forecastOrderSDO.getString("wareHouseCode");
//
//                try {
//                    QueryGoodsDetailListRequest queryGoodsListRequest = new QueryGoodsDetailListRequest();
//                    queryGoodsListRequest.setChannelCode(channelCode);
//                    queryGoodsListRequest.setSalesmanCode(salesmanCode);
//                    queryGoodsListRequest.setSaleChannelCode(orgSaleChannelCode);
//                    queryGoodsListRequest.setOrganizationCode(organizationCode);
//                    queryGoodsListRequest.setDepartmentCode(orgSaleDepartmentCode);
//                    queryGoodsListRequest.setWarehouseCode(warehouseCode);
//                    //queryGoodsListRequest.setRecentlyUsedItemIdList(goodsIdList);
//                    Result<List<GoodsFavorites>> goodsFavoritesResult = favoritesService.queryGoodsFavorites(new QueryGoodsFavoritesRequest());
//                    log.info("查询货品收藏夹出参:"+JSONObject.toJSONString(goodsFavoritesResult));
//                    if (Objects.nonNull(goodsFavoritesResult)&&CollectionUtils.isNotEmpty(goodsFavoritesResult.getResult())){
//                        GoodsFavorites goodsFavorites = goodsFavoritesResult.getResult().get(0);
//                        String goodsList = goodsFavorites.getGoodsList();
//                        if (org.apache.commons.lang3.StringUtils.isNotBlank(goodsList)&&!"[]".equalsIgnoreCase(goodsList)){
//                            List<GoodsFavoritesItem> goodsFavoritesItems = JSONObject.parseArray(goodsList, GoodsFavoritesItem.class);
//                            List<String> goodsCodes = goodsFavoritesItems.stream().map(GoodsFavoritesItem::getGoodsCode).collect(Collectors.toList());
//                            queryGoodsListRequest.setGoodsFavoritesList(goodsCodes);
//                        }
//                    }
//
//                    Callable<List<ScItemGoods>> scItemCallableWithAddress = () -> forecastOrderLineQueryService.queryGoodsDetailList(queryGoodsListRequest).getResult().getScItemGoodsList();
//                    taskAddressScItem = new FutureTask<>(scItemCallableWithAddress);
//                    new Thread((Runnable) taskAddressScItem).start();
//                } catch (Exception e) {
//                    log.error("根据地址附带组织信息查询货品列表:", e);
//                }
//
//        }
//
//        long l4 = System.currentTimeMillis();
//        //预报子单单价和总价分元单位转换，总价和总数量统计
//        int orderCountNum = 0;
//        double orderCountAmount = 0.0;
//        JSONArray forecastOrderLineSDOList = forecastOrderSDO.getJSONArray("forecastOrderLineSDOList");
//        List<JSONObject> lineList = new ArrayList<>();
//        if (Objects.nonNull(forecastOrderLineSDOList) && CollectionUtils.isNotEmpty(forecastOrderLineSDOList)) {
//            for (Object o : forecastOrderLineSDOList) {
//                JSONObject orderLine = (JSONObject) o;
//                orderLine.put("unitPrice", orderLine.getDoubleValue("unitPrice") / 100);
//                double totalAmount = orderLine.getDoubleValue("totalFee") / 100;
//                int quantity = orderLine.getInteger("quantity");
//                orderLine.put("totalFee", orderLine.getDoubleValue("totalFee") / 100);
//                orderLine.put("goodsCode", orderLine.getString("goodsCode"));
//                lineList.add(orderLine);
//
//                orderCountAmount += totalAmount;
//                orderCountNum += quantity;
//            }
//            forecastOrderSDO.put("forecastOrderLineSDOList", lineList);
//        }
//
//        //销售订单子单分元单位转换，总价和总数量统计
//        JSONArray orderDetailList = forecastOrderSDO.getJSONArray("orderDetailList");
//        List<JSONObject> detailList = new ArrayList<>();
//
//        if (Objects.nonNull(orderDetailList) && CollectionUtils.isNotEmpty(orderDetailList)) {
//            for (Object o : orderDetailList) {
//                JSONObject orderLine = (JSONObject) o;
//                orderLine.put("unitPrice", orderLine.getDoubleValue("unitPrice") / 100);
//                orderLine.put("activityUnitPrice", orderLine.getDoubleValue("activityUnitPrice") / 100);
//                double totalAmount = orderLine.getDoubleValue("totalAmount") / 100;
//                int quantity = orderLine.getInteger("quantity");
//                orderLine.put("totalAmount", totalAmount);
//                orderLine.put("activityTotalAmount", orderLine.getDoubleValue("activityTotalAmount") / 100);
//                //订单总金额，订单总数
//                orderCountAmount += totalAmount;
//                orderCountNum += quantity;
//
//                if (StringUtils.isNotBlank(orderLine.getString("rejectReason"))) {
//                    QueryEnumValueSingleResponse queryEnumValueSingleResponse = otsPlatformEnhanceService.queryEnumValueSingle(new QueryEnumValueSingleRequest() {{
//                        setCode("refuseReason");
//                        setValueData(orderLine.getString("rejectReason"));
//                    }});
//                    if (Objects.nonNull(queryEnumValueSingleResponse) && StringUtils.isNotBlank(queryEnumValueSingleResponse.getName())) {
//                        orderLine.put("refuseReasonText", queryEnumValueSingleResponse.getName());
//                    }
//                }
//                detailList.add(orderLine);
//            }
//            forecastOrderSDO.put("orderDetailList", detailList);
//        }
//        forecastOrderSDO.put("orderCountNum", orderCountNum);
//        forecastOrderSDO.put("orderCountAmount", new BigDecimal(orderCountAmount).setScale(2, RoundingMode.DOWN).doubleValue());
//        long l5 = System.currentTimeMillis();
//        log.info("计算订单详情明细耗时:" + (l5 - l4));
//
//        String orderTypeValue = String.valueOf(forecastOrderSDO.get("orderType"));
//
//        //订单类型数据异常处理
//        if (Objects.isNull(orderTypeValue)) {
//            log.error("小程序销售预报订单单据类型缺失：", JSONObject.toJSONString(forecastOrderSDO));
//            return null;
//        }
//
//        if (needLoadSelectList) {
//
//            //配送方式
//            deliveryType = JSONObject.parseObject(JSONObject.parseObject(JSONObject.toJSONString(otsPlatformEnhanceService.queryEnumValues(new QueryEnumValuesRequest() {{
//                setCode("shipMethod");
//            }}))).getString("result"), List.class);
//            //发货仓
//            long l8 = System.currentTimeMillis();
//            QueryCargoZoneListWithAccessRequest queryCargoZoneListWithAccessRequest = new QueryCargoZoneListWithAccessRequest();
//            queryCargoZoneListWithAccessRequest.setTypeList(Collections.singletonList(3));
//            List<WarehouseInfo> sendList = bcOtsService.queryCargoZoneListWithAccess(queryCargoZoneListWithAccessRequest).getResult();
//            if (CollectionUtils.isNotEmpty(sendList)) {
//                deliveryHouse = sendList.stream().map(x -> {
//                    Info info = new Info();
//                    info.setLabel(x.getName());
//                    info.setValue(x.getId());
//                    return info;
//                }).collect(Collectors.toList());
//            }
//            long l9 = System.currentTimeMillis();
//            log.info("查询发货仓耗时:" + (l9 - l8));
//        }
//
//        EmployeeGetCurrentLoginResponse employeeGetCurrentLoginResponse = bcOtsService.employeeGetCurrentLogin();
//        if (Objects.nonNull(employeeGetCurrentLoginResponse)){
//            String organizationType = employeeGetCurrentLoginResponse.getRelatedOrganizationType();
//            if (Integer.parseInt(organizationType)>=104){
//                //是否禁用采购订单号
//                Result<List<OrganizationSDO>> loginEmployOrganizationPermissionsPrice = otsPlatformEnhanceService.getLoginEmployOrganizationPermissionsPrice(new GetLoginEmployOrganizationPermissionsPriceRequest() {{
//                    setType(104);
//                }});
//                if (Objects.nonNull(loginEmployOrganizationPermissionsPrice)&&CollectionUtils.isNotEmpty(loginEmployOrganizationPermissionsPrice.getResult())){
//                    OrganizationSDO organizationSDO = loginEmployOrganizationPermissionsPrice.getResult().get(0);
//                    if (SHANGHAI_ORG_CODE.equalsIgnoreCase(organizationSDO.getCode())){
//                        createSelectList.setDisableRefNo(Boolean.TRUE);
//                    }
//                }
//
//            }
//        }
//        createSelectList.setOrderType(FILTER_ORDER_TYPE);
//        createSelectList.setDeliveryType(deliveryType);
//        createSelectList.setDeliveryWarehouse(deliveryHouse);
//        createSelectList.setForecastOrderSDO(forecastOrderSDO);
//        createSelectList.setInputOrderType((PLAN_ORDER_TYPE == renderRequest.getInputType() ? "plan" : "sale"));
//        if (needLoadSelectList) {
//            try {
//                createSelectList.setScItemGoodsList(taskAddressScItem.get());
//            } catch (InterruptedException | ExecutionException e) {
//                log.error("小程序预报销售订单获取货品列表异常:", e.getMessage());
//                e.printStackTrace();
//            }
//        }
//        return createSelectList;
//    }
//
//    @Override
//    public Object asyncSubmit(AsyncSubmitRequest asyncSubmitRequest) {
//
//        //从客户地址上取组织信息 如果没有异常，应取此货品集合
//        Future<List<ScItemGoods>> taskAddressScItem = null;
//
//        JSONObject requestInput = (JSONObject) JSONObject.toJSON(asyncSubmitRequest.getRequestInput());
//        log.info("asyncSubmitRequest:" + JSONObject.toJSONString(asyncSubmitRequest.getRequestInput()));
//        String addressCode = requestInput.getJSONObject("fields").getJSONObject("updateFields").getString("addressValue");
//        String addressId = requestInput.getJSONObject("fields").getJSONObject("updateFields").getString("addressId");
//        JSONObject bizModel = requestInput.getJSONObject("fields").getJSONObject("bizModel");
//        //页面模块上的其他模块的选中value
//        JSONObject tempSaveValue = requestInput.getJSONObject("fields").getJSONObject("tempSaveValue");
//
//        //对bizModel里面的forecastSDO的addressId赋值
//        tempSaveValue.put("addressId",addressId);
//        tempSaveValue.put("addressCode",addressCode);
//        bizModel.put("tempSaveValue", tempSaveValue);
//        bizModel.getJSONObject("forecastOrderSDO").put("addressId",addressId);
//        PageQueryAddressListByPrincipalResponse listResult = otsPlatformEnhanceService.pageQueryAddressListByPrincipal(new PageQueryAddressListByPrincipalRequest() {{
//            setId(addressId);
//        }});
//
//        if (Objects.nonNull(listResult) && CollectionUtils.isNotEmpty(listResult.getResult())) {
//            JSONObject relationInfo = (JSONObject) JSONObject.toJSON(listResult.getResult().get(0));
//
//            String itemGroup = relationInfo.getString("itemGroup");
//            String channelCode = relationInfo.getString("channelCode");
//            String customerCode = relationInfo.getString("customerCode");
//            String organizationCode = relationInfo.getString("orgSaleOrganizationCode");
//            String orgSaleDepartmentCode = relationInfo.getString("orgSaleDepartmentCode");
//            String orgSaleChannelCode = relationInfo.getString("orgSaleChannelCode");
//            String salesmanCode = relationInfo.getString("principal");
//            bizModel.getJSONObject("forecastOrderSDO").put("customerName",relationInfo.getString("customerName"));
//
//            try {
//                //查询用户信用额度
//                QueryCreditRequest queryCreditRequest = new QueryCreditRequest();
//                queryCreditRequest.setChannelCode(channelCode);
//                queryCreditRequest.setCustomerCode(customerCode);
//                queryCreditRequest.setOrganizationCode(organizationCode);
//                queryCreditRequest.setItemGroupCode(itemGroup);
//                Result<CreditReponse> creditReponseResult = creditQueryService.queryCreditBalance(queryCreditRequest);
//                if (creditReponseResult.isSuccess() && Objects.nonNull(creditReponseResult.getResult())) {
//                    relationInfo.put("creditBalance", creditReponseResult.getResult().getBalance());
//                }
//
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            bizModel.put("chooseAddress", relationInfo);
//
//            try {
//                QueryAllocateRelationRequest queryAllocateRelationRequest = new QueryAllocateRelationRequest();
//                queryAllocateRelationRequest.setAllocateRelationSDO(new AllocateRelationSDO() {{
//                    setAddressCode(addressCode);
//                    setOrganizationCode(relationInfo.getString("orgSaleOrganizationCode"));
//                    setSaleChannelCode(relationInfo.getString("orgSaleChannelCode"));
//                }});
//
//                //查询客户的关联关系，用户查询出货品仓，客户姓名等关系
//                Result<List<AllocateRelationSDO>> pageQueryAllocateRelationResponse = allocateRelationReadService.pageQueryAllocateRelation(queryAllocateRelationRequest);
//                if (Objects.nonNull(pageQueryAllocateRelationResponse) && CollectionUtils.isNotEmpty(pageQueryAllocateRelationResponse.getResult()))
//                    bizModel.put("wareHouseInfo", pageQueryAllocateRelationResponse.getResult().get(0));
//                    bizModel.put("wareHouseCode", pageQueryAllocateRelationResponse.getResult().get(0).getWareHouseCode());
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//
//            try {
//                QueryGoodsDetailListRequest queryGoodsListRequest = new QueryGoodsDetailListRequest();
//                queryGoodsListRequest.setChannelCode(channelCode);
//                queryGoodsListRequest.setSalesmanCode(salesmanCode);
//                queryGoodsListRequest.setSaleChannelCode(orgSaleChannelCode);
//                queryGoodsListRequest.setOrganizationCode(organizationCode);
//                queryGoodsListRequest.setDepartmentCode(orgSaleDepartmentCode);
//                if (Objects.nonNull(bizModel.get("wareHouseCode"))&&StringUtils.isNotBlank(String.valueOf(bizModel.get("wareHouseCode")))){
//                    queryGoodsListRequest.setWarehouseCode(String.valueOf(bizModel.get("wareHouseCode")));
//                }
//                Result<List<GoodsFavorites>> goodsFavoritesResult = favoritesService.queryGoodsFavorites(new QueryGoodsFavoritesRequest());
//                log.info("查询货品收藏夹出参:"+JSONObject.toJSONString(goodsFavoritesResult));
//                if (Objects.nonNull(goodsFavoritesResult)&&CollectionUtils.isNotEmpty(goodsFavoritesResult.getResult())){
//                    GoodsFavorites goodsFavorites = goodsFavoritesResult.getResult().get(0);
//                    String goodsList = goodsFavorites.getGoodsList();
//                    if (org.apache.commons.lang3.StringUtils.isNotBlank(goodsList)&&!"[]".equalsIgnoreCase(goodsList)){
//                        List<GoodsFavoritesItem> goodsFavoritesItems = JSONObject.parseArray(goodsList, GoodsFavoritesItem.class);
//                        List<String> goodsCodes = goodsFavoritesItems.stream().map(GoodsFavoritesItem::getGoodsCode).collect(Collectors.toList());
//                        queryGoodsListRequest.setGoodsFavoritesList(goodsCodes);
//                    }
//                }
//                Callable<List<ScItemGoods>> scItemCallableWithAddress = () -> forecastOrderLineQueryService.queryGoodsDetailList(queryGoodsListRequest).getResult().getScItemGoodsList();
//                taskAddressScItem = new FutureTask<>(scItemCallableWithAddress);
//                new Thread((Runnable) taskAddressScItem).start();
//            } catch (Exception e) {
//                log.error("根据地址附带组织信息查询货品列表:", e.getMessage());
//                e.printStackTrace();
//            }
//
//        } else {
//            return Result.fail("", "查询收货地址异常");
//        }
//
//        //配送方式
//        List<Info> deliveryType = JSONObject.parseObject(JSONObject.parseObject(JSONObject.toJSONString(otsPlatformEnhanceService.queryEnumValues(new QueryEnumValuesRequest() {{
//            setCode("shipMethod");
//        }}))).getString("result"), List.class);
//        //发货仓
//        QueryCargoZoneListWithAccessRequest queryCargoZoneListWithAccessRequest = new QueryCargoZoneListWithAccessRequest();
//        queryCargoZoneListWithAccessRequest.setTypeList(Arrays.asList(3));
//        List<WarehouseInfo> sendList = bcOtsService.queryCargoZoneListWithAccess(queryCargoZoneListWithAccessRequest).getResult();
//        if (CollectionUtils.isNotEmpty(sendList)) {
//            List<Info> deliveryHouse = sendList.stream().map(x -> {
//                Info info = new Info();
//                info.setLabel(x.getName());
//                info.setValue(x.getId());
//                return info;
//            }).collect(Collectors.toList());
//            bizModel.put("deliveryWarehouse", deliveryHouse);
//        }
//        bizModel.put("disableRefNo", Boolean.FALSE);
//        EmployeeGetCurrentLoginResponse employeeGetCurrentLoginResponse = bcOtsService.employeeGetCurrentLogin();
//        if (Objects.nonNull(employeeGetCurrentLoginResponse)){
//            String organizationType = employeeGetCurrentLoginResponse.getRelatedOrganizationType();
//            if (Integer.parseInt(organizationType)>=104){
//                //是否禁用采购订单号
//                Result<List<OrganizationSDO>> loginEmployOrganizationPermissionsPrice = otsPlatformEnhanceService.getLoginEmployOrganizationPermissionsPrice(new GetLoginEmployOrganizationPermissionsPriceRequest() {{
//                    setType(104);
//                }});
//                if (Objects.nonNull(loginEmployOrganizationPermissionsPrice)&&CollectionUtils.isNotEmpty(loginEmployOrganizationPermissionsPrice.getResult())){
//                    OrganizationSDO organizationSDO = loginEmployOrganizationPermissionsPrice.getResult().get(0);
//                    if (SHANGHAI_ORG_CODE.equalsIgnoreCase(organizationSDO.getCode())){
//                        bizModel.put("disableRefNo", Boolean.TRUE);
//                    }
//                }
//
//            }
//        }
//
//        bizModel.put("orderType", FILTER_ORDER_TYPE);
//        bizModel.put("deliveryType", deliveryType);
//        try {
//
//        bizModel.put("scItemGoodsList", taskAddressScItem.get());
//
//        } catch (InterruptedException | ExecutionException e) {
//            e.printStackTrace();
//        }
//        return bizModel;
//    }
//
//    @Override
//    public Object submit(SubmitRequest submitRequest) {
//        log.info("submitRequest:" + JSONObject.toJSONString(submitRequest));
//        JSONObject requestInput = (JSONObject) JSONObject.toJSON(submitRequest.getRequestInput());
//        JSONObject result = new JSONObject();
//
//        //如果是取消提报
//        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(submitRequest.getRequestInput());
//        String cancelId = jsonObject.getJSONObject("fields").getString("cancelId");
//        if (StringUtils.isNotBlank(cancelId)) {
//            CancelForecastOrderRequest cancelForecastOrderRequest = new CancelForecastOrderRequest();
//            cancelForecastOrderRequest.setIds(Arrays.asList(cancelId));
//            return otsForecastSalesService.cancelForecastOrder(cancelForecastOrderRequest);
//        }
//
//        String submitType = requestInput.getJSONObject("fields").getJSONObject("submitFields").getJSONObject("bottomButton").getString("submitType");
//        JSONObject submitFields = requestInput.getJSONObject("fields").getJSONObject("submitFields");
//
//        if (Objects.nonNull(submitFields)) {
//            CreateForecastOrderParamsResponse forecastOrderParams = planOrderSubmit(submitFields, submitType);
//            if (null == forecastOrderParams.getSuccess()) {
//                result.put("success", false);
//                result.put("message", "预报单创建提交异常");
//                return result;
//            }
//
//            return forecastOrderParams;
//        } else {
//            result.put("success", false);
//            result.put("message", "提交参数空白");
//            return result;
//        }
//
//    }
//
//    private CreateForecastOrderParamsResponse planOrderSubmit(JSONObject submitFields, String submitType) {
//        ForecastOrderSDO forecastOrderInputRequest = new ForecastOrderSDO();
//
//
//        String addressCode = submitFields.getString("addressCode");
//        String addressId = submitFields.getString("addressId");
//        if (StringUtils.isNotBlank(addressCode)) {
//            /*Result<List<CustomerAddressSDO>> listResult = customerAddressQueryService.pageQueryCustomerAddress(new QueryAddressRequest() {{
//                setAddressCode(addressCode);
//            }});*/
//
//            PageQueryAddressListByPrincipalResponse listResult ;
//            listResult= otsPlatformEnhanceService.pageQueryAddressListByPrincipal(new PageQueryAddressListByPrincipalRequest() {{
//                setId(addressId);
//            }});
//
//            if (Objects.isNull(listResult) || CollectionUtils.isEmpty(listResult.getResult())){
//                listResult= otsPlatformEnhanceService.pageQueryAddressListByPrincipal(new PageQueryAddressListByPrincipalRequest() {{
//                    setAddressCode(addressId);
//                }});
//            }
//
//
//            /*List<CustomerAddressSDO> list = otsPlatformEnhanceService.pageQueryAddressList(new PageQueryAddressListRequest() {{
//                setAddressCode(addressCode);
//            }}).getResult();*/
//
//            if (Objects.nonNull(listResult) && CollectionUtils.isNotEmpty(listResult.getResult())) {
//                CustomerAddressSDO customerAddressSDO =  JSONObject.parseObject(JSONObject.toJSONString(listResult.getResult().get(0)),CustomerAddressSDO.class);
//                BeanUtils.copyProperties(customerAddressSDO, forecastOrderInputRequest, "id");
//                forecastOrderInputRequest.setSaleChannelCode(customerAddressSDO.getOrgSaleChannelCode());
//                forecastOrderInputRequest.setSaleChannelName(customerAddressSDO.getOrgSalesChannelName());
//                forecastOrderInputRequest.setOrganizationCode(customerAddressSDO.getOrgSaleOrganizationCode());
//                forecastOrderInputRequest.setOrganizationName(customerAddressSDO.getOrgSalesOrganizationName());
//                forecastOrderInputRequest.setDepartmentCode(customerAddressSDO.getOrgSaleDepartmentCode());
//                forecastOrderInputRequest.setDepartmentName(customerAddressSDO.getOrgSalesDepartmentName());
//                forecastOrderInputRequest.setCustomerCode(customerAddressSDO.getCustomerCode());
//                forecastOrderInputRequest.setCustomerName(customerAddressSDO.getCustomerName());
//                forecastOrderInputRequest.setChannelCode(customerAddressSDO.getChannelCode());
//                forecastOrderInputRequest.setChannelName(customerAddressSDO.getChannelName());
//                forecastOrderInputRequest.setSalesmanCode(customerAddressSDO.getPrincipal());
//                forecastOrderInputRequest.setSalesmanName(customerAddressSDO.getPrincipalName());
//                forecastOrderInputRequest.setBisUnitCode(customerAddressSDO.getOrgBussinessUnitCode());
//            }
//        }
//        String orderId = submitFields.getString("orderId");
//
//
//        forecastOrderInputRequest.setId(orderId);
//        forecastOrderInputRequest.setStatus(ForecastStatusEnum.DRAFT.getNumValue());
//        //待回复状态点击保存，状态保持待回复
//        if (submitFields.get("toBeReplied") != null) {
//            forecastOrderInputRequest.setStatus(ForecastStatusEnum.WAITING_FOR_REPLY.getNumValue());
//        }
//        forecastOrderInputRequest.setOrderType(submitFields.getString("orderTypeCode"));
//        forecastOrderInputRequest.setReceiveAddressCode(addressCode);
//        forecastOrderInputRequest.setCustomerReferenceNo(submitFields.getString("customerReferenceNo"));
//        forecastOrderInputRequest.setRemark(submitFields.getString("remark"));
//        forecastOrderInputRequest.setTransportModeCode(submitFields.getString("transportModeCode"));
//        forecastOrderInputRequest.setCustomerExpectTDate(getDateTime(Long.valueOf(submitFields.getString("customerExpectTDate"))));
//        forecastOrderInputRequest.setWareHouseCode(submitFields.getString("wareHouseCode"));
//        //添加发货仓name
//        if (StringUtils.isNotBlank(submitFields.getString("wareHouseCode"))) {
//            Result<WarehouseInfo> warehouseInfoResult = unifiedInventoryService.queryWarehouseById(new QueryWarehouseByIdRequest() {{
//                setId(submitFields.getString("wareHouseCode"));
//            }});
//            if (Objects.nonNull(warehouseInfoResult) && warehouseInfoResult.isSuccess() && Objects.nonNull(warehouseInfoResult.getResult())) {
//                forecastOrderInputRequest.setWareHouseName(warehouseInfoResult.getResult().getName());
//            }
//        }
//
//
//        log.info("forecastOrderInputRequest" + JSONObject.toJSONString(forecastOrderInputRequest));
//        CreateForecastOrderParamsRequest createForecastOrderParamsRequest = new CreateForecastOrderParamsRequest();
//
//        createForecastOrderParamsRequest.setForecastOrderSDOList(new ArrayList<ForecastOrderSDO>() {{
//            add(forecastOrderInputRequest);
//        }});
//
//        createForecastOrderParamsRequest.setHasSubOrders(true);
//
//        // CreateForecastOrderParamsResponse forecastOrderParams = otsForecastSalesService.createForecastOrderParams(createForecastOrderParamsRequest);
//
//
//        //货品明细的编辑 通过主单ID去查询下属的所有子单，然后进行删除的哪些子单的判断 最后把剩余子单调用更新预报订单接口 （interface内部实现了增改判断）
//        PageQueryForecastRequest pageQueryForecastRequest = new PageQueryForecastRequest();
//        pageQueryForecastRequest.setId(orderId);
//        pageQueryForecastRequest.setStart(0);
//        pageQueryForecastRequest.setLimit(100);
//        Result<List<QueryForecastLineResponse>> orderLineResult = null;
//        try {
//            orderLineResult = forecastOrderLineQueryService.pageQueryOrderLine(pageQueryForecastRequest);
//        } catch (Exception e) {
//            log.error("打印异常", e);
//            return new CreateForecastOrderParamsResponse() {{
//                setResult(e.getMessage());
//                setMessage(e.getMessage());
//                setSuccess(false);
//            }};
//        }
//
//
//        List<String> existLineOrderIds = new ArrayList<>();
//        if (orderLineResult.isSuccess() && CollectionUtils.isNotEmpty(orderLineResult.getResult())) {
//            existLineOrderIds = orderLineResult.getResult().stream().map(QueryForecastLineResponse::getId).collect(Collectors.toList());
//
//            /*
//            DeleteForecastLineDetailRequest deleteForecastLineDetailRequest = new DeleteForecastLineDetailRequest();
//            deleteForecastLineDetailRequest.setIds(collect);
//            Result<DeleteForecastLineDetailReponse> lineDelete = forecastOrderLineWriteService.deleteForecastLine(deleteForecastLineDetailRequest);
//*/
//
//        }
//
//        JSONArray goodDetailArray = submitFields.getJSONArray("goodDetail");
//        CreateForecastOrderParamsResponse forecastOrderParams = null;
//      //  if (Objects.nonNull(goodDetailArray) && CollectionUtils.isNotEmpty(goodDetailArray)) {
//
//            List<ForecastOrderLineSDO> orderLineSDOList = Nullable.stream(goodDetailArray).map(o -> castToOrderLine(o)).collect(Collectors.toList());
//            List<String> inputLineOrderIds = Nullable.stream(orderLineSDOList).map(o -> String.valueOf(o.getId())).collect(Collectors.toList());
//
//            //删除input中没有的子单
//            if (CollectionUtils.isNotEmpty(existLineOrderIds)) {
//                List<String> shouldDeleteIds = Nullable.stream(existLineOrderIds).filter(o -> !inputLineOrderIds.contains(o)).collect(Collectors.toList());
//
//                if (CollectionUtils.isNotEmpty(shouldDeleteIds)) {
//                    List<Long> ids=Nullable.stream(shouldDeleteIds).map(Long::parseLong).collect(Collectors.toList());
//                    DeleteLineWithRelease deleteLineWithRelease = new DeleteLineWithRelease();
//                    deleteLineWithRelease.setIds(ids);
//                    forecastOrderLineWriteService.deleteForecastLineWithRelease(deleteLineWithRelease);
//                }
//            }
//
//            Nullable.stream(orderLineSDOList).forEach(o -> o.setMainOrderId(orderId));
//            forecastOrderInputRequest.setForecastOrderLineSDOList(orderLineSDOList);
//            createForecastOrderParamsRequest.setHasSubOrders(true);
//            log.info("创建订单入参：" + JSONObject.toJSONString(createForecastOrderParamsRequest));
//            try {
//                forecastOrderParams = otsForecastSalesService.createForecastOrderParams(createForecastOrderParamsRequest);
//            } catch (Exception e) {
//                log.error("打印错误日志", e);
//                return new CreateForecastOrderParamsResponse() {{
//                    setResult(e.getMessage());
//                    setMessage(e.getMessage());
//                    setSuccess(false);
//                }};
//            }
//
//            log.info("创建返回结果" + JSONObject.toJSONString(forecastOrderParams));
//        //}
//
//        if ("submit".equalsIgnoreCase(submitType)) {
//            EmployeeGetCurrentLoginResponse currentLoginResponse = bcOtsService.employeeGetCurrentLogin();
//
//            SubmitForecastRequest submitForecastRequest = new SubmitForecastRequest();
//
//            List<ForecastOrderSDO> forecastOrderSDOList = createForecastOrderParamsRequest.getForecastOrderSDOList();
//
//
//            ApiContext apiContext = new ApiContext();
//            if (Objects.nonNull(currentLoginResponse)) {
//                BeanUtils.copyProperties(currentLoginResponse, apiContext);
//            }
//            submitForecastRequest.setForecastOrderSDOList(forecastOrderSDOList);
//            submitForecastRequest.setApiContext(apiContext);
//            Result<Boolean> booleanResult = null;
//            try {
//                booleanResult = forecastOrderWriteService.submitForecast(submitForecastRequest);
//
//            } catch (Exception e) {
//                log.error("打印异常日志", e);
//                return new CreateForecastOrderParamsResponse() {{
//                    setResult(e.getMessage());
//                    setMessage(e.getMessage());
//                    setSuccess(false);
//                }};
//
//            }
//            Result<Boolean> finalBooleanResult = booleanResult;
//            return new CreateForecastOrderParamsResponse() {{
//                setMessage(finalBooleanResult.getMessage());
//                setResult(finalBooleanResult.getResult());
//                setSuccess(finalBooleanResult.isSuccess());
//            }};
//        }
//
//        log.info("预报订单创建返回结果" + JSONObject.toJSONString(forecastOrderParams));
//        return forecastOrderParams;
//
//    }
//
//    private ForecastOrderLineSDO castToOrderLine(Object o) {
//        JSONObject source = (JSONObject) o;
//        ForecastOrderLineSDO target = new ForecastOrderLineSDO();
//        target.setId(StringUtils.isNotBlank(source.getString("id")) ? source.getDouble("id").longValue() : null);
//        target.setScItemTitle(source.getString("scItemTitle"));
//        target.setScItemId(source.getString("scItemId"));
//        target.setInventoryUnit(source.getString("inventoryUnit"));
//        target.setInventoryUnitCode(source.getString("inventoryUnitCode"));
//        target.setQuantity(source.getString("quantity"));
//        target.setSaleUnit(source.getString("saleUnit"));
//        target.setUnitConvert(source.getString("unitConvert"));
//        target.setActivityCode(source.getString("activityCode"));
//        target.setActivityNumber(source.getString("activityNumber"));
//        target.setDetailRemark(source.getString("detailRemark"));
//        target.setActivityPriceRemark(source.getString("activityPriceRemark"));
//        target.setActualTotalReplyAmount(source.getInteger("actualTotalReplyAmount"));
//        target.setSaleUnitCode(source.getString("saleUnitCode"));
//        target.setGoodsCode(source.getString("goodsCode"));
//        target.setSerialNumber(source.getString("serialNumber"));
//        if (CollectionUtils.isNotEmpty(source.getJSONArray("saleUnitList"))) {
//            target.setSaleUnitList(source.getJSONArray("saleUnitList").toJavaList(SelectCombox.class));
//        }
//        target.setCategoryChildCode(source.getString("categoryChildCode"));
//        target.setCategoryChildDesc(source.getString("categoryChildDesc"));
//        target.setCategoryCode(source.getString("categoryDesc"));
//        target.setCategoryDesc(source.getString("category"));
//
//        if (Objects.nonNull(source.getDouble("unitPrice"))) {
//            target.setUnitPrice(source.getLong("unitPrice"));
//        }
//
//        if (Objects.nonNull(source.getDouble("totalFee"))) {
//            target.setTotalFee(source.getLong("totalFee"));
//
//        }
//
//        return target;
//    }
//
//    private String getTopLevelCode(String id, Integer type) {
//        Result<List<OrganizationSDO>> topOrganizationList = organizationQueryService.getTopOrganizationList(new IdQueryRequest() {{
//            setId(id);
//            setType(type);
//        }});
//
//        if (Objects.nonNull(topOrganizationList) && CollectionUtils.isNotEmpty(topOrganizationList.getResult())) {
//            List<OrganizationSDO> collect = topOrganizationList.getResult().stream().filter(o -> o.getType() == 103).collect(Collectors.toList());
//
//            if (CollectionUtils.isNotEmpty(collect)) {
//                return Optional.ofNullable(collect.get(0).getId()).orElse("");
//            }
//
//        }
//        return "";
//    }
//
//    private Date getDateTime(Long charDateTime) {
//        return new Date(charDateTime);
//    }
//
//    @Data
//    public class CreateSelectList {
//        private List<Info> orderType;
//        private List<Info> customerAddress;
//        private List<Info> deliveryType;
//        private List<Info> deliveryWarehouse;
//        private List<ScItemGoods> scItemGoodsList;
//        private Object forecastOrderSDO;
//        private String inputOrderType;
//        private Boolean disableRefNo;
//    }
//
//    @Data
//    public static class Info {
//        private String label;
//        private String value;
//    }
//}
